﻿using MediatR;
using Medical.Api.Read.Application.Command.PackagingSterilization;
using Medical.Api.Read.Dto.PackagingSterilization;
using Medical.Domain.PackagingSterilization;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;

namespace Medical.Api.Read.Application.Handler.PackagingSterilization
{
    /// <summary>
    /// 获取已灭菌信息列表的命令处理
    /// </summary>
    public class GetSterilizedCommandHandlter : IRequestHandler<GetSterilizedCommand, ApiResult<List<sterilizationDtos>>>
    {

        /// <summary>
        /// 灭菌注册仓储
        /// </summary>
        private readonly IBaseRepository<SterilizationRegistration> sterilizationRegistrationRep;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="sterilizationRegistrationRep">灭菌注册仓储</param>
        public GetSterilizedCommandHandlter(IBaseRepository<SterilizationRegistration> sterilizationRegistrationRep)
        {
            this.sterilizationRegistrationRep = sterilizationRegistrationRep;
        }
        public async Task<ApiResult<List<sterilizationDtos>>> Handle(GetSterilizedCommand request, CancellationToken cancellationToken)
        {
            try
            {
                //获取已灭菌的记录信息
                var query = sterilizationRegistrationRep.GetAll()
                    .Where(x => !x.IsDeleted && x.Status == 1)
                    .OrderByDescending(x => x.CompletionTime);
                var result = query.ToList();
                var sterilizationDtosList = result.Select(x => new sterilizationDtos
                {
                    Id = x.Id,
                    BatchNumber = x.BatchNumber,
                    SterilizationMode = x.SterilizationMode,
                    EquipmentId = x.EquipmentId,
                    SterilizationBatch = x.SterilizationBatch,
                    Operator = x.Operator,
                    StartTime = x.StartTime,
                    SterilizationDuration = x.SterilizationDuration,
                    Status = x.Status,
                    CompletionOperator = x.CompletionOperator,
                    CompletionTime = x.CompletionTime,
                    SterilizationResult = x.SterilizationResult,
                    EquipmentPackageIds = x.EquipmentPackageIds
                }).ToList();
                return new ApiResult<List<sterilizationDtos>>
                {
                    Code = ApiEnums.Success,
                    Data = sterilizationDtosList,
                    Msg = "获取已完成灭菌信息成功"
                };

            }
            catch (Exception ex)
            {
                return new ApiResult<List<sterilizationDtos>>
                {
                    Code = ApiEnums.Error,
                    Data = null,
                    Msg = $"获取已完成灭菌信息异常：{ex.Message}"
                };
            }
        }
    }
}
